package com.usian.comment.service.impl;

import com.usian.comment.service.CommentLikeService;
import com.usian.model.comment.dto.CommentLikeDto;
import com.usian.model.comment.pojos.ApComment;
import com.usian.model.comment.pojos.ApCommentLike;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CommentLikeServiceImpl implements CommentLikeService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Value("${likeCount}")
    private Integer likeCount;

    @Override
    public ResponseResult like(CommentLikeDto dto) {
        if (dto ==null && dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        ApUser user = AppThreadLocalUtils.getUser();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if(dto.getOperation()==0){
            //点赞  只能一次
            Query query=new Query();
            query.addCriteria(Criteria.where("authorId").is(user.getId()).and("commentId").is(dto.getCommentId()));
            List<ApCommentLike> commentLikeList = mongoTemplate.find(query, ApCommentLike.class);
            if(commentLikeList.size()<=likeCount-1){
                apComment.setLikes(apComment.getLikes()+1);
                mongoTemplate.save(apComment);

                ApCommentLike apCommentLike = new ApCommentLike();
                apCommentLike.setAuthorId(user.getId());
                apCommentLike.setCommentId(apComment.getId());
                apCommentLike.setOperation(dto.getOperation());
                mongoTemplate.save(apCommentLike);
            }
        }else if(dto.getOperation()==1){
            //取消点赞
            apComment.setLikes(apComment.getLikes() <= 0 ? 0 : apComment.getLikes() - 1);
            mongoTemplate.save(apComment);

            Query query=new Query();
            query.addCriteria(Criteria.where("authorId").is(user.getId()).and("commentId").is(dto.getCommentId()));
            mongoTemplate.remove(query,ApCommentLike.class);

        }

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes",apComment.getLikes());
        return ResponseResult.okResult(resultMap);
    }
}
